from django.contrib import admin
from .models import Tag, CursorRule

@admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
    """标签管理"""
    list_display = ('name', 'category', 'created_at')
    list_filter = ('category',)
    search_fields = ('name',)
    ordering = ('category', 'name')

@admin.register(CursorRule)
class CursorRuleAdmin(admin.ModelAdmin):
    """Cursor规则管理"""
    list_display = ('title', 'author', 'status', 'created_at', 'updated_at')
    list_filter = ('status', 'tags', 'created_at')
    search_fields = ('title', 'content', 'author__username')
    filter_horizontal = ('tags',)
    raw_id_fields = ('author',)
    readonly_fields = ('created_at', 'updated_at')
    list_per_page = 20
    
    fieldsets = (
        (None, {
            'fields': ('title', 'content', 'author'),
        }),
        ('分类与状态', {
            'fields': ('tags', 'status'),
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',),
        }),
    )
    
    def save_model(self, request, obj, form, change):
        """保存模型时，如果是新建规则，则将当前用户设置为作者"""
        if not change:
            obj.author = request.user
        super().save_model(request, obj, form, change)
